package com.aduerr.v1shouyin.mvp.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.aduerr.v1shouyin.App;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.entity.CardType;
import com.aduerr.v1shouyin.entity.KaQuanXiangQingEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.mvp.activity.CardDetailNewActivity;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 类名: YouhuiFragment
 * 此类用途: ---
 *
 * @Date: 2017-10-24 15:42
 * @描述: 次卡核销页面
 */
public class TimeCardsFragment extends Fragment {
    Unbinder unbinder;
    @BindView(R.id.rv_time_card)
    RecyclerView mRvTimeCard;
    @BindView(R.id.srl_time_cards)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.empty_view)
    LinearLayout mLlEmpty;
    Context context;

    int pager = 1;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_time_card, null,
                false);
        unbinder = ButterKnife.bind(this, inflate);
        refreshLayout.setRefreshHeader(new ClassicsHeader(getContext()));
        refreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pager = 1;
                loadData();
                refreshlayout.finishRefresh();
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pager++;
                loadData();
                refreshlayout.finishLoadmore(); //加载完成
            }
        });
        loadData();
        return inflate;
    }


    /**
     * 加载数据
     */
    public void loadData() {
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("page", pager+"");
        addParams.put("pageSize", "20");
        APIRetrofit.getAPIService().GetFrequencyCardInfos(RXRequest.getXingPosParams(addParams
                , getContext()))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<KaQuanXiangQingEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(KaQuanXiangQingEntity entity) {
                        if(entity != null && entity.getSuccess() == 1 && entity.getData() != null) {
                            if(pager == 1) {
                                listEntities.clear();
                            }
                            for(int i = 0; i < entity.getData().size(); i++) {
                                listEntities.addAll(entity.getData().get(i).getList());
                            }

                            for(int j = 0; j < listEntities.size(); j++) {
                                listEntities.get(j).setId(j);
                            }
                            setAdapter();
                            if(listEntities.isEmpty()) {
                                mLlEmpty.setVisibility(View.VISIBLE);
                            } else {
                                mLlEmpty.setVisibility(View.GONE);
                            }


                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            ToastUtils.showToast(App.getApp(), "网络异常");
                        } else if(e instanceof ConnectException) {
                            ToastUtils.showToast(App.getApp(), "连接失败");

                        } else {
                            ToastUtils.showToast(App.getApp(), "检查网络状态");
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }


    @Override
    public void onDestroyView() {
        if(unbinder != null) {
            unbinder.unbind();
        }
        cardAdapter = null;
        super.onDestroyView();
    }


    List<KaQuanXiangQingEntity.DataBean.ListBean> listEntities = new ArrayList<>();
    public BaseQuickAdapter<KaQuanXiangQingEntity.DataBean.ListBean, BaseViewHolder> cardAdapter;

    public void setAdapter() {
        if(cardAdapter == null) {
            cardAdapter = new BaseQuickAdapter<KaQuanXiangQingEntity.DataBean.ListBean,
                    BaseViewHolder>(R.layout.item_fragment_time_card, listEntities) {
                @Override
                protected void convert(BaseViewHolder helper,
                                       KaQuanXiangQingEntity.DataBean.ListBean item) {
                    if(item.getId()==0){
                        helper.setText(R.id.item_time_card_date,item.getDate());
                        helper.setGone(R.id.item_time_card_date,true);
                    }else if(item.getId() != 0){
                        if(item.getDate().equals(listEntities.get(item.getId()-1).getDate())){
                            helper.setGone(R.id.item_time_card_date,false);
                        }else{
                            helper.setGone(R.id.item_time_card_date,true);
                            helper.setText(R.id.item_time_card_date,item.getDate());
                        }

                    }

                    helper.setText(R.id.tv_hx_title, item.getName());
                    helper.setText(R.id.tv_hx_zhekou, item.getDescription());
                    helper.setText(R.id.tv_hx_time, item.getUsetime().split(" ")[1]);
                    helper.setText(R.id.tv_hx_seller, item.getSiteusername());
                }
            };

            cardAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    KaQuanXiangQingEntity.DataBean.ListBean listBean =
                            listEntities.get(position);
                    Intent intent = new Intent(getActivity(), CardDetailNewActivity.class);
                    intent.putExtra("type", CardType.WX.name());
                    intent.putExtra("Data", listBean);
                    intent.putExtra("tag", "xianxia");
                    startActivity(intent);
                }
            });

            mRvTimeCard.setHasFixedSize(true);
            mRvTimeCard.setNestedScrollingEnabled(false);
            LinearLayoutManager manager = new LinearLayoutManager(context,
                    LinearLayoutManager.VERTICAL, false);
            mRvTimeCard.setLayoutManager(manager);
            mRvTimeCard.setAdapter(cardAdapter);

        } else {
            cardAdapter.notifyDataSetChanged();
        }
    }

}
